<template>
  <div class="product-manage-page">
    <header class="page-header">
      <h2>产品管理</h2>
      <div class="actions">
        <button class="btn primary" @click="openCreate">新建产品</button>
  <input v-model="keyword" placeholder="搜索产品名称/编码格式" />
      </div>
    </header>

    <section class="product-table-wrapper" v-if="products.length">
      <table class="product-table">
        <thead>
          <tr>
            <th style="width: 160px">产品名称</th>
            <th style="width: 180px">SKU编码格式</th>
            <th style="width: 120px">产品类型</th>
            <th style="width: 150px">创建时间</th>
            <th style="width: 150px">修改时间</th>
            <th style="width: 160px">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="p in filtered" :key="p.id">
            <td>{{ p.name }}</td>
            <td>{{ p.codePattern }}</td>
            <td>{{ p.type }}</td>
            <td>{{ formatDate(p.createdAt) }}</td>
            <td>{{ formatDate(p.updatedAt) }}</td>
            <td class="ops">
              <button class="btn link" @click="edit(p)">编辑</button>
              <button class="btn link danger" @click="remove(p.id)">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
    </section>
    <p v-else class="empty-tip">暂无产品，请新建。</p>

    <dialog ref="dialogRef" class="product-dialog">
      <form method="dialog" class="dialog-body" @submit.prevent="save">
        <h3>{{ current?.id ? '编辑产品' : '新建产品' }}</h3>
        <div class="form-grid">
          <label>名称<input v-model="form.name" required /></label>
          <label>SKU编码格式说明
            <input v-model="form.codePattern" placeholder="例如：0718xxxxxxx" required />
          </label>
          <label>产品类型
            <select v-model="form.type" required>
              <option value="">请选择</option>
              <option v-for="t in productTypes" :key="t" :value="t">{{ t }}</option>
            </select>
          </label>
        </div>
        <div class="dialog-actions">
          <button class="btn" value="cancel" @click="closeDialog">取消</button>
          <button class="btn primary" type="submit">保存</button>
        </div>
      </form>
    </dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';

interface Product { id: string; name: string; codePattern: string; type: string; createdAt: number; updatedAt: number; }

const keyword = ref('');
const productTypes = ['建材成品', '三框成品', '三框线条', '自制建材线条', '外购建材线条'];
const products = ref<Product[]>([{
  id: '1', name: 'PE户外地板', codePattern: '0718xxxxxx', type: '建材成品', createdAt: Date.now() - 86400000, updatedAt: Date.now()
}]);

// 简单模糊匹配（子序列匹配），例如 输入 "phdb" 可匹配 "PE户外地板"
function fuzzySubsequence(text: string, pattern: string) {
  let ti = 0, pi = 0;
  while (ti < text.length && pi < pattern.length) {
    if (text[ti] === pattern[pi]) pi++;
    ti++;
  }
  return pi === pattern.length;
}

const filtered = computed(() => {
  const kw = keyword.value.trim().toLowerCase();
  if (!kw) return products.value;
  return products.value.filter(p => {
    const nameLower = p.name.toLowerCase();
    // 产品名称：大小写忽略 + 子字符串 或 子序列模糊
    if (nameLower.includes(kw) || fuzzySubsequence(nameLower, kw)) return true;
    // 仍然保留对编码格式字段的普通包含（非必须，可移除）
    return p.codePattern.toLowerCase().includes(kw);
  });
});

const dialogRef = ref<HTMLDialogElement | null>(null);
const current = ref<Product | null>(null);
const form = ref({ name: '', codePattern: '', type: '' });

function openCreate() {
  current.value = null;
  form.value = { name: '', codePattern: '', type: '' };
  dialogRef.value?.showModal();
}
function edit(p: Product) {
  current.value = p;
  form.value = { name: p.name, codePattern: p.codePattern, type: p.type };
  dialogRef.value?.showModal();
}
function closeDialog() { dialogRef.value?.close(); }
function save() {
  if (current.value) {
    current.value.name = form.value.name;
    current.value.codePattern = form.value.codePattern;
    current.value.type = form.value.type;
  // category removed
    current.value.updatedAt = Date.now();
  } else {
    const now = Date.now();
  products.value.unshift({ id: Math.random().toString(36).slice(2), createdAt: now, updatedAt: now, ...form.value });
  }
  closeDialog();
}
function remove(id: string) { products.value = products.value.filter(p => p.id !== id); }
function formatDate(ts: number) { const d = new Date(ts); return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')} ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`; }
</script>

<style scoped>
.product-manage-page { display: flex; flex-direction: column; gap: 1rem; }
.page-header { display: flex; flex-direction: column; gap: .75rem; }
.page-header h2 { margin: 0; }
.actions { display: flex; gap: .75rem; align-items: center; }
.actions input { flex: 1; padding: .5rem .6rem; border: 1px solid #cbd5e1; border-radius: 4px; }
.btn { cursor: pointer; border: 1px solid #64748b; background: #fff; padding: .4rem .9rem; border-radius: 4px; font-size: 14px; }
.btn.primary { background: #1d4ed8; color: #fff; border-color: #1d4ed8; }
.btn.link { background: transparent; border: none; color: #1d4ed8; padding: .25rem .5rem; }
.btn.link.danger { color: #dc2626; }
.product-table-wrapper { overflow: auto; }
.product-table { width: 100%; border-collapse: collapse; font-size: 14px; }
.product-table th, .product-table td { border: 1px solid #e2e8f0; padding: .5rem .6rem; text-align: left; }
.product-table thead { background: #f1f5f9; }
.ops { display: flex; gap: .25rem; }
.empty-tip { color: #64748b; }
.product-dialog::backdrop { background: rgba(0,0,0,.35); }
.product-dialog { border: none; padding: 0; border-radius: 8px; width: 720px; max-width: 95vw; }
.dialog-body { display: flex; flex-direction: column; gap: 1rem; padding: 1.25rem 1.5rem 1.5rem; }
.form-grid { display: grid; grid-template-columns: repeat(auto-fill,minmax(180px,1fr)); gap: .75rem; }
.form-grid label { display: flex; flex-direction: column; font-size: 12px; gap: 4px; color: #334155; }
.form-grid input, .form-grid select { padding: .45rem .55rem; border: 1px solid #cbd5e1; border-radius: 4px; font-size: 14px; }
.error-text { margin: 4px 0 0; color: #dc2626; font-weight: 500; }
.btn.primary[disabled] { opacity: .6; cursor: not-allowed; }
.dialog-actions { display: flex; justify-content: flex-end; gap: .75rem; margin-top: .5rem; }
.dialog-body h3 { margin: 0 0 .25rem; font-size: 18px; }
</style>
